import config from '../configuration.js';
import axios from 'axios';
import redisHelper from '../redisHelper.js';


let access_token = '';
let expires_time = 0;
async function GetOpenID(code) {
    let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${config.applet_param.APPID}&secret=${config.applet_param.APPSECRET}&js_code=${code}&grant_type=authorization_code`;
    try {
        let res = await _get(url);
        console.info('获取OpenID成功', `请求URL==>${url}  响应==>${JSON.stringify(res)}`);
        return { code: 0, data: res };
    } catch (error) {
        console.error(console.log('用Code获取OpneID出错', `请求URL==>${url}`, error.message));
        return { code: 1, msg: '用Code获取OpneID出错:' + error.message };
    }
}

//获取小程序access_token
async function getAccessToken() {
    if (access_token && expires_time > Date.now()) {
        return { code: 1, data: access_token };
    }
    let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.applet_param.APPID}&secret=${config.applet_param.APPSECRET}`;
    try {
        let res = await _get(url);
        console.info('获取AccessToken成功', `请求URL==>${url}  响应==>${JSON.stringify(res)}`);
        let data = res;
        access_token = data.access_token;
        expires_time = Date.now() + data.expires_in * 1000;
        return { code: 0, access_token };
    } catch (error) {
        console.error(console.log('获取AccessToken出错', `请求URL==>${url}`, error.message));
        return { code: 1, msg: '获取AccessToken出错:' + error.message };
    }
}

//小程序手机号快速验证
async function getPhoneNumber(code) {
    await getAccessToken();
    let url = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${access_token}`;
    let data={code}
    try {
        let res =await axios.post(url,data);
        console.info('获取手机号成功', `请求URL==>${url}  响应==>${JSON.stringify(res.data)}`);
        return { code: 0, data: res.data};
    } catch (error) {
        console.error(console.log('获取手机号出错', `请求URL==>${url}`, error.message));
        return { code: 1, msg: '获取手机号出错:' + error.message };
    }

}



async function _get(url) {
    try {
        let response = await axios.get(url);
        return response.data;
    } catch (error) {
        console.error('GET request error:', error.message);
        return {errMsg:error.message};
    }
}


class WxService {
    static async getAccessToken() {
        const accssTokenKey = `wx_access_token`;
        const expires = 6000;
        const accessTokenKey = await redisHelper.get(accssTokenKey);
        if (accessTokenKey) {
            return accessTokenKey;
        }

        const ret = await axios.get('https://api.weixin.qq.com/cgi-bin/token', {
            params: {
                grant_type: 'client_credential',
                appid: config.applet_param.APPID,
                secret: config.applet_param.APPSECRET,
            },
        });

        if (!ret.data?.access_token) {
            logger.info('微信获取token失败', ret);
            return;
        }

        await redisHelper.set(accssTokenKey, ret.data.access_token, expires);
        return ret.data.access_token;
    }

    static async generateUrllink(params) {
        const accessToken = await this.getAccessToken();
        const ret = await axios.post(
            'https://api.weixin.qq.com/wxa/generate_urllink',
            {
                ...params,
            },
            {
                params: {
                    access_token: accessToken,
                },
            }
        );
        return ret.data;
    }
}

export { GetOpenID,getPhoneNumber, WxService };


// async function test() {
//     let res = await getAccessToken();
//     console.log(JSON.stringify(res));
// }

// test();
